<?php

namespace app\controller;


use app\BaseController;
use app\traits\CommonTrait;
use app\validate\PhoneCheck;
use app\validate\PhoneCodeCheck;
use Overtrue\EasySms\EasySms;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\Request;
use app\model\User;

class Sms extends BaseController
{
    use CommonTrait;

    public function smsSend()
    {
        //注册 1注册 2忘记密码
        $type = Request::post('type', 1);
        $phone = Request::post('phone');
        try {
            validate(PhoneCheck::class)->check([
                'phone' => $phone,
                'type' => $type
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }

        $phoneExist = User::where(['phone'=>$phone])->findOrEmpty();
        switch ($type){
            case 1:
                if(!$phoneExist->isEmpty()){
                    return $this->apiJson(-1,'手机号已经注册');
                }
                break;
            case 2:
                if($phoneExist->isEmpty()){
                    return $this->apiJson(-1,'账号不存在');
                }
                break;
        }
        return $this->sendCode($type, $phone);
    }

    public function smsVerify()
    {
        //注册
        $type = Request::post('type', 1);
        $phone = Request::post('phone');
        $code = Request::post('code');
        try {
            validate(PhoneCheck::class)->check([
                'phone' => $phone,
                'type' => $type,
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }
        return $this->codeVerify($type, $phone, $code);
    }

}